import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ChatClient extends JFrame {
    private JTextField textField;
    private JTextArea chatArea;
    private PrintWriter out;
    private BufferedReader in;

    public ChatClient(String host, int port) {
        super("Chat Client");
        setupUI();

        try {
            Socket socket = new Socket(host, port);
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            listenForMessages();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void setupUI() {
        textField = new JTextField(20);
        chatArea = new JTextArea(15, 30);

        JPanel panel = new JPanel();
        panel.add(textField);
        JButton button = new JButton("Send");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sendMessage();
            }
        });
        panel.add(button);

        add(panel, "South");
        add(new JScrollPane(chatArea), "Center");

        setSize(400, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    private void sendMessage() {
        out.println(textField.getText());
        textField.setText("");
    }

    private void listenForMessages() {
        new Thread(() -> {
            String fromServer;
            try {
                while ((fromServer = in.readLine()) != null) {
                    String finalFromServer = fromServer;
                    SwingUtilities.invokeLater(() -> chatArea.append("Server: " + finalFromServer + "\n"));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

    public static void main(String[] args) {
        new ChatClient("localhost", 9090); // 假设服务器运行在本地机器上
    }
}